import React from 'react';
import { Table, Space, Button, Modal, Form, Radio, Input, Popconfirm, message } from "antd";
import './App.css';

const FormItem = Form.Item;
const RadioGroup = Radio.Group;

type IColumnType = "CUSTOMIZE" | "FIXED" | "REMARK" | "USER_FILL";

enum EColumn {
  CUSTOMIZE = "自定义列",
  FIXED = "固定列",
  REMARK = "备注列",
  USER_FILL = "用户手填列",
}

interface IColumn {
  /**
   * 子级
   */
  children: IColumn[] | null;
  /**
   * id
   */
  id: string;
  /**
   * 层级
   */
  level: number;
  /**
   * 名称
   */
  name?: null | string;
  /**
   * 父ID 为-1则为根节点
   */
  parentId: string;
  /**
   * 表头名称
   */
  title: string | null;
  /**
   * 列类型
   */
  type: IColumnType;
}

function App() {
  const [form] = Form.useForm();
  const [data, setData] = React.useState<IColumn[]>([{
    "id": "code",
    "parentId": "-1",
    "children": null,
    "name": null,
    "level": 0,
    "title": "编号",
    "type": "FIXED",
  },
  {
    "id": "name",
    "parentId": "-1",
    "children": null,
    "name": null,
    "level": 0,
    "title": "名称",
    "type": "FIXED",
  },
  {
    "id": "remark",
    "parentId": "-1",
    "children": null,
    "name": null,
    "level": 0,
    "title": "工料概要说明",
    "type": "FIXED",
  },])
  const [visable, setVisable] = React.useState<boolean>(false);
  const [editData, setEditData] = React.useState<IColumn | null>(null);
  const [parentData, setParentData] = React.useState<IColumn | null>(null);
  const [currentId, setCurrentId] = React.useState<number>(1);
  const columns = [
    {
      title: '表头名称',
      dataIndex: 'title',
      key: 'title',
    },
    {
      title: '列类型',
      dataIndex: 'type',
      key: 'type',
      render(type: IColumnType) {
        return EColumn[type]
      }
    },
    {
      title: '操作',
      dataIndex: 'operation',
      key: 'operation',
      render(value: null, record: IColumn) {
        return <Space>
          <Button key="add" type="link" disabled={canEdit(record)} onClick={() => addChildItem(record)}>
            新建子级
          </Button>
          <Button key="edit" type="link" disabled={canEdit(record)} onClick={() => editItem(record)}>
            编辑
          </Button>
          <Popconfirm
            title="删除提示"
            description="你是否确定删除该项目?"
            onConfirm={() => deleteItem(record)}
            okText="是"
            cancelText="否"
          >
            <Button danger key="delete" type="link" disabled={canEdit(record)}>
              删除
            </Button>
          </Popconfirm>
        </Space>
      }
    },
  ]
  const canEdit = (record: IColumn) => {
    return record.id === 'code' || record.id === 'name' || record.id === 'remark'
  }
  const restForm = () => {
    setVisable(false)
    setEditData(null)
    form.resetFields()
    setParentData(null)
  }
  const addItem = () => {
    setEditData(null)
    setVisable(true)
  }
  const addChildItem = (record: IColumn) => {
    setParentData(record)

    setEditData(null)
    setVisable(true)
  }
  const editItem = (record: IColumn) => {
    form.setFieldValue('type', record.type)
    form.setFieldValue('title', record.title)
    
    setEditData(record)
    setVisable(true)
  }
  const findItemToDelete = (ids: string[], dataList: IColumn[], index: number = 0) => {
    const idArr:string[] = ids.slice(0, index + 1)

    const findItem = dataList.find(item => item.id == idArr.join('-'))
    
    if (findItem) {
      const parentId = ids.slice(0, ids.length - 1).join('-') 
      const deleteId = ids.join('-') 
      
      if (findItem.id == parentId) {
        findItem.children = (findItem.children || []).filter(item => item.id !== deleteId)
        setData(JSON.parse(JSON.stringify(data)))
        
        message.success({
          type: 'success',
          content: '删除成功',
        });
      } else {
        findItemToDelete(ids, findItem.children || [], index + 1)
      }
    }
  }
  const deleteItem = (record: IColumn) => {
    if (record.parentId != '-1') {
      const ids = record.id.split('-')
      findItemToDelete(ids, data)
    } else {
      setData(data.filter(item => item.id != record.id))
      
      message.success({
        type: 'success',
        content: '删除成功',
      });
    }
    
  }
  const handleOk = () => {
    form.validateFields().then(async (values: IColumn) => {
      
      if (parentData && !editData) { // 新建子级
        const parentDataChildren = parentData && parentData.children
        if (parentDataChildren && parentDataChildren.length) {
          const lastChild = parentDataChildren[parentDataChildren.length - 1]
          parentData.children = [...parentDataChildren, {
            ...values,
            id: `${parentData.id}-${lastChild.id ? Number(lastChild.id) + 1 : 1}`,
            "parentId": parentData.id,
          }]
          
        } else if(parentData) {
          parentData.children = [{
            ...values,
            id: `${parentData.id}-${1}`,
            "parentId": parentData.id,
          }]
        }
        setData(JSON.parse(JSON.stringify(data)))
        message.success({
          type: 'success',
          content: '添加成功',
        });
      } else if (!parentData && !editData) {
        const rest = data.slice(0, data.length - 1)
        const last = data[data.length - 1]
        setData([...rest, {
          ...values,
          id: String(currentId),
          "parentId": "-1",
        }, last])
        setCurrentId(currentId + 1)
        message.success({
          type: 'success',
          content: '添加成功',
        });
      } else if (editData) {
        editData.type = values.type
        editData.title = values.title
        setData(JSON.parse(JSON.stringify(data)))
        message.success({
          type: 'success',
          content: '编辑成功',
        });
      }
      restForm()
    }).catch(err => {
      console.log(err, 'err');
    });
  }
  const handleCancel = () => {
    restForm()
  }

  const sortListFun = (data: IColumn) => {
    const dataList = data.children
    if (dataList) {
      dataList.sort((a:IColumn, b: IColumn) => (a.title || '').localeCompare((b.title || '')))
      dataList.forEach((item: IColumn) => {
        sortListFun(item)
      })
    }

  }

  const sortList = () => {
    const startList = data.slice(0, 2)
    const centerList = data.slice(2, data.length - 1)
    const endList = data.slice(data.length - 1, data.length)

    const newCenterList = centerList.sort((a:IColumn, b: IColumn) => (a.title || '').localeCompare((b.title || '')))
    
    centerList.forEach(item => {
        sortListFun(item)
    })
    
    setData([...startList, ...centerList, ...endList])

    message.success({
      type: 'success',
      content: '排序成功',
    });
  }

  const validName = [
    {
      required: true,
      whitespace: true,
      message: "请输入名字",
    }
  ]
  const validType = [
    {
      required: true,
      whitespace: true,
      message: "请选择类型",
    }
  ]
  return (
    <div className="App">
      <header className="App-header">
        <Space className='main-btn-list'>
          <Button onClick={addItem}>新建</Button>
          <Button onClick={sortList}>排序</Button>
        </Space>
        <Table rowKey="id" className="main-table" dataSource={data} columns={columns} pagination={false} />
        <Modal
          centered
          className="common-modal"
          title={editData ? '编辑列' : '添加列'}
          open={visable}
          onOk={handleOk}
          onCancel={handleCancel}
        >
          <Form form={form}>
            <FormItem
              label="类型"
              name="type"
              rules={validType}
            >
              <RadioGroup>
                <Radio value={'CUSTOMIZE'}>{EColumn.CUSTOMIZE}</Radio>
                {/* <Radio value={'FIXED'}>{EColumn.FIXED}</Radio> */}
                <Radio value={'REMARK'}>{EColumn.REMARK}</Radio>
                <Radio value={'USER_FILL'}>{EColumn.USER_FILL}</Radio>
              </RadioGroup>
            </FormItem>
            <FormItem
              label="名称"
              name="title"
              rules={validName}
            >
              <Input />
            </FormItem>
          </Form>
        </Modal>
      </header>
    </div>
  );
}

export default App;
